package com.db.derby;

import com.db.derby.DBConnection;
import com.db.history.messages.Message;
import com.db.history.messages.PrivateMessage;
import com.db.services.DateOperations;
import com.db.services.Settings;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by Student on 27.11.2014.
 */
public class DBAccess {


    public String getHistoryFromTable(String tableName, String filter ) {
        StringBuffer sb = new StringBuffer();
//        String selectString = "SELECT * from "+ tableName + " where date_time{fn TIMESTAMPADD(SQL_TSI_DAYS, -" + Settings.HISTORY_PERIOD_DAYS + ", CURRENT_TIMESTAMP)} "
//                + ((filter == null || "".equals(filter))?"": " and " + filter);

        String selectString = "SELECT * from "+ tableName
                + ((filter == null || "".equals(filter))?"": " where " + filter);

        System.out.println(selectString);
        try (


                PreparedStatement statement = DBConnection.getConn()
                        .prepareStatement(selectString);
                ResultSet resultSet = statement.executeQuery()) {
            printHistory(sb, resultSet);

        } catch (Exception e) {
            System.out.println("Can't get history");
            e.getStackTrace();
        }

        return sb.toString();
    }


    public String getHistory( ) {
       return getHistoryFromTable("history", "");
    }

    public String getRoomHistory(String roomName) {

        return getHistoryFromTable("history", "room = '" + roomName + "'");
    }

    private void printHistory(StringBuffer sb, ResultSet resultSet) throws SQLException {
        while (resultSet.next()) {
            sb.append(DateOperations.getDataString(resultSet.getTimestamp("date_time"))).append("\t");
            sb.append(resultSet.getString("room")).append("\t");
            sb.append(resultSet.getString("user_name")).append("\t:");
            sb.append(resultSet.getString("message")).append("\n");
        }
    }

    public String getPrivateHistory(String name) {
        return getHistoryFromTable("private_history", " (addressee = '" + name + "' or user_name = '" + name + "')");
    }

    public void addMessage(Message message) {
        try {
            try (Statement stmt = DBConnection.getConn().createStatement()) {
                stmt.executeUpdate("insert into app.history (user_name, message, room) values ('" + message.getUserName() + "', '" +  message.getMessage() + "', '" + message.getRoom() + "')");
            }
        } catch (SQLException e) {
            System.out.println("Can't save message to db");
            e.printStackTrace();
        }
    }

    public void addPrivateMessage(PrivateMessage message) {
        try {
            try (Statement stmt = DBConnection.getConn().createStatement()) {
                stmt.executeUpdate("insert into app.PRIVATE_HISTORY (user_name, message, room, ADDRESSEE) values ('" + message.getUserName() + "', '" +  message.getMessage() + "', '" + message.getRoom() + "', '" + message.getAddressee() + "')");
            }
        } catch (SQLException e) {
            System.out.println("Can't save private message to db");
            e.printStackTrace();
        }
    }

    public boolean login(String name, String password) {

        String selectString = "SELECT * from  USERS where USER_NAME = '" + name + "'";
//        System.out.println(selectString);
        try (

                PreparedStatement statement = DBConnection.getConn()
                        .prepareStatement(selectString);
                ResultSet resultSet = statement.executeQuery()) {

                if (resultSet.next()) {
                    System.out.println("User " + name + " exist");

                    if (password.equals(resultSet.getString("password"))) {
                        System.out.println(name + " auth accepted");
                        return true;
                    }
                    else {
                        System.out.println(name + "'s password is not correct");
                        return false;
                    }
                }
                else
                {
                    try (Statement stmt = DBConnection.getConn().createStatement()) {
                        stmt.executeUpdate("insert into app.USERS (user_name, PASSWORD) values ('" +name + "', '" + password + "')");
                        System.out.println("User was added");
                    }

                    return true;
                }


        } catch (Exception e) {
            System.out.println("Error with user auth");
            e.getStackTrace();
        }


        return false;
    }


}
